/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.sun.ShipperProcessor;

import com.sun.Entity.Shippingorder;
import com.sun.Facade.ShippingorderFacadeLocal;
import exceptions.InvalidEstimatedEndProductionDateException;
import exceptions.UnknownOrderException;
import java.util.Calendar;
import java.util.Date;
import javax.ejb.EJB;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.ejb.Stateless;

/**
 *
 * @author test
 */
@WebService()
@Stateless()
public class CalculatePenalityWS {

    @EJB
    private ShippingorderFacadeLocal shippingorderFacade;

    /**
     * Web service operation
     */
    @WebMethod(operationName = "operation")
    public Float operation(
            @WebParam(name = "OrderID") String OrderID,
            @WebParam(name = "EstimatedEndProductionDate") Date EstimatedEndProductionDate)
            throws
            UnknownOrderException,
            InvalidEstimatedEndProductionDateException {

        // Verification OrderID existance
        Shippingorder Order = shippingorderFacade.find(OrderID);
        if (Order == null) {
            throw new UnknownOrderException();
        }

        // Verification If EstimatedEndProductionDate is a valid value (> today)
        if (EstimatedEndProductionDate == null) {
            throw new InvalidEstimatedEndProductionDateException();
        }
        if (EstimatedEndProductionDate.before(Calendar.getInstance().getTime())) {
            throw new InvalidEstimatedEndProductionDateException();
        }

        // Calculate Impact
        float Penality = 0;
        if (EstimatedEndProductionDate.after(Order.getEstimatedshippingdate())) {
            float DaysBetweenDates = getDaysBetweenDates(EstimatedEndProductionDate, Order.getEstimatedshippingdate());
            float OrderAmount = Order.getAmount();
            Penality = OrderAmount*20/100;
            Penality = Penality * DaysBetweenDates;
            return Penality;
        }
        return Penality;
    }

    public static float getDaysBetweenDates(Date theEarlierDate, Date theLaterDate) {
        float result = Float.POSITIVE_INFINITY;
        if (theEarlierDate != null && theLaterDate != null) {
            final long MILLISECONDS_PER_DAY = 1000 * 60 * 60 * 24;
            Calendar aCal = Calendar.getInstance();
            aCal.setTime(theEarlierDate);
            long aFromOffset = aCal.get(Calendar.DST_OFFSET);
            aCal.setTime(theLaterDate);
            long aToOffset = aCal.get(Calendar.DST_OFFSET);
            long aDayDiffInMili = (theLaterDate.getTime() + aToOffset) - (theEarlierDate.getTime() + aFromOffset);
            result = aDayDiffInMili / MILLISECONDS_PER_DAY;
        }
        return result;
    }
}
